<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox, FormInstance } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { TSystemNotice } from '../../../../Types/system'
import { standardDateTime } from '../../../../Tools/Time/date'
import {
	publishSystemNotice,
	getSystemNotice,
	deleteSystemNotice,
	updateSystemNotice
} from '../../../../api/system/notice'

// 常量定义
const noticeType = [
	{ label: '系统公告', value: 'notice' },
	{ label: '版本更新', value: 'version' }
] as const
const importantOption = [
	{ label: '普通', value: '普通' },
	{ label: '重要', value: '重要' }
] as const
const defaultForm: TSystemNotice = {
	title: '',
	content: '',
	type: 'notice',
	version: '',
	important: '普通',
	status: true,
	createTime: '',
	updateTime: '',
	createBy: ''
}

// 状态定义
const loading = ref(false)
const noticeList = ref<TSystemNotice[]>([])
const formRef = ref<FormInstance>()
// 弹窗状态
const dialogVisible = ref(false)
const dialogTitle = ref('')
const loadingDialog = ref(false)
const currentNotice = ref<TSystemNotice>({ ...defaultForm })

// 方法定义
// 列表操作
const getNoticeList = async () => {
	loading.value = true
	try {
		const res = await getSystemNotice()
		noticeList.value = res.data.data
	} catch {
		ElMessage.error('获取公告列表失败')
	} finally {
		loading.value = false
	}
}

const handleStatusChange = async (row: TSystemNotice) => {
	try {
		await updateSystemNotice(row)
		ElMessage.success('状态更新成功')
	} catch {
		row.status = !row.status
		ElMessage.error('状态更新失败')
	}
}

const handleDelete = (row: TSystemNotice) => {
	ElMessageBox.confirm('确定要删除该公告吗？', '提示', {
		type: 'warning'
	}).then(async () => {
		try {
			if (row.id) {
				await deleteSystemNotice(row.id)
				ElMessage.success('删除成功')
				getNoticeList()
			}
		} catch {
			ElMessage.error('删除失败')
		}
	})
}

// 弹窗操作
const openDialog = (type: 'add' | 'edit', row?: TSystemNotice) => {
	dialogTitle.value = type === 'add' ? '发布公告' : '编辑公告'
	currentNotice.value = row ? { ...row } : { ...defaultForm }
	dialogVisible.value = true
	loadingDialog.value = false
}

// 提交表单
const noticeSubmit = async (notice: TSystemNotice) => {
	if (!formRef.value) return
	// 等待表单验证
	await formRef.value.validate(async (valid) => {
		if (!valid) return

		try {
			if (notice.id) {
				await updateSystemNotice(notice)
				ElMessage.success('编辑成功')
			} else {
				await publishSystemNotice(notice)
				ElMessage.success('发布成功')
			}
			dialogVisible.value = false
			getNoticeList()
		} catch {
			ElMessage.error(notice.id ? '编辑失败' : '发布失败')
		}
	})
}

// 重置表单
const resetForm = () => {
	currentNotice.value = { ...defaultForm }
	formRef.value?.resetFields()
}

// 表单验证规则
const formRule = {
	title: [{ required: true, max: 10, message: '请输入公告标题', trigger: 'blur' }],
	content: [{ required: true, max: 100, message: '请输入公告内容', trigger: 'blur' }],
	type: [{ required: true, message: '请选择公告类型', trigger: 'change' }],
	important: [{ required: true, message: '请选择重要程度', trigger: 'change' }],
	version: [{ required: true, message: '请输入版本号', trigger: 'blur' }]
}

// 生命周期
onMounted(getNoticeList)
</script>

<template>
	<el-card class="notice-card">
		<!-- 卡片头部 -->
		<template #header>
			<div class="card-header">
				<h2>系统公告管理</h2>
				<el-button type="primary" @click="openDialog('add')">
					<el-icon><Plus /></el-icon>发布
				</el-button>
			</div>
		</template>

		<!-- 表格部分 -->
		<el-table :data="noticeList" v-loading="loading" :height="300">
			<el-table-column prop="createTime" label="创建时间" width="120">
				<template #default="{ row }">{{ standardDateTime(row.createTime) }}</template>
			</el-table-column>

			<el-table-column prop="title" label="标题" width="100" show-overflow-tooltip />
			<el-table-column prop="content" label="内容" width="200" show-overflow-tooltip />

			<el-table-column prop="type" label="类型" width="80">
				<template #default="{ row }">
					<el-tag :type="row.type === 'notice' ? 'success' : 'warning'">
						{{ row.type === 'notice' ? '公告' : `更新` }}
					</el-tag>
				</template>
			</el-table-column>

			<el-table-column prop="important" label="重要性" width="80">
				<template #default="{ row }">
					<el-tag :type="row.important === '重要' ? 'danger' : 'info'">
						{{ row.important }}
					</el-tag>
				</template>
			</el-table-column>

			<el-table-column prop="status" label="状态" width="80">
				<template #default="{ row }">
					<el-switch v-model="row.status" @change="handleStatusChange(row)" />
				</template>
			</el-table-column>

			<el-table-column label="操作" width="100" fixed="right">
				<template #default="{ row }">
					<el-button-group>
						<el-button type="primary" link @click="openDialog('edit', row)">编辑</el-button>
						<el-button type="danger" link @click="handleDelete(row)">删除</el-button>
					</el-button-group>
				</template>
			</el-table-column>
		</el-table>

		<!-- 弹窗表单 -->
		<el-dialog
			:title="dialogTitle"
			v-model="dialogVisible"
			align-center
			width="600px"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<div v-loading="loadingDialog">
				<el-form ref="formRef" :model="currentNotice" :rules="formRule" label-width="120px">
					<el-form-item label="公告标题" prop="title" style="width: 46vh">
						<el-input v-model="currentNotice.title" placeholder="公告标题（最多10字）" />
					</el-form-item>

					<el-form-item label="公告内容" prop="content">
						<el-input
							v-model="currentNotice.content"
							type="textarea"
							:rows="4"
							placeholder="请输入公告内容（最多100字）"
						/>
					</el-form-item>

					<el-form-item label="公告类型" prop="type" style="width: 40vh">
						<el-select v-model="currentNotice.type">
							<el-option
								v-for="item in noticeType"
								:key="item.value"
								:label="item.label"
								:value="item.value"
							/>
						</el-select>
					</el-form-item>

					<el-form-item label="重要程度" prop="important" style="width: 35vh">
						<el-select v-model="currentNotice.important">
							<el-option
								v-for="item in importantOption"
								:key="item.value"
								:label="item.label"
								:value="item.value"
							/>
						</el-select>
					</el-form-item>

					<el-form-item
						v-if="currentNotice.type === 'version'"
						label="版本号"
						prop="version"
						style="width: 45vh"
					>
						<el-input v-model="currentNotice.version" placeholder="请输入版本号" />
					</el-form-item>

					<el-form-item label="是否启用" prop="status">
						<el-switch v-model="currentNotice.status" />
					</el-form-item>

					<el-form-item>
						<el-button type="primary" @click="noticeSubmit(currentNotice)">
							{{ currentNotice.id ? '更新' : '发布' }}
						</el-button>
						<el-button @click="resetForm">重置</el-button>
						<el-button @click="dialogVisible = false">取消</el-button>
					</el-form-item>
				</el-form>
			</div>
		</el-dialog>
	</el-card>
</template>
